//
//  LBCoureseDetailVC.m
//  V-Learn
//
//  Created by Apple on 2019/1/3.
//  Copyright © 2019 yxk. All rights reserved.
//

#import "LBCoureseDetailVC.h"
#import "LBCouresePackageCell.h"
#import "LBCoureseVideoCell.h"
#import "LBCourseYinpinCell.h"
#import "LBCourseImageViewCell.h"
#import "LBTeacherIntroduceCell.h"
#import "LBKeshiDetailVC.h"
#import "LBCourseOutputDTOListModel.h"
#import "LBCourseHourOutputDTOList.h"
#import "LBTeacherModel.h"

#import "ZFTableHeaderView.h"
#import "ZFPlayerControlView.h"
#import <ZFPlayer/ZFPlayer.h>
#import "ZFAVPlayerManager.h"
#import "LWShareService.h"
#import <UMCommon/UMCommon.h>
#import <UMShare/UMShare.h>
#import "TestTableViewController.h"
#import "LBKeshDetailVC.h"
#import "ZSDTCoreTextCell.h"
#import "ZSDTCoreTextTools.h"
#import "LBKeshDetailsVC.h"
@interface LBCoureseDetailVC ()<UITableViewDelegate,UITableViewDataSource,DTAttributedTextContentViewDelegate,DTLazyImageViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UILabel *priceLab;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *teacherDataArray;
@property (nonatomic, strong) LBCourseOutputDTOListModel *model;
@property (nonatomic, strong) LBCourseHourOutputDTOList *hourOutputModel;
@property (nonatomic, strong) UILabel *sectionTitle;

@property (nonatomic, strong) ZFTableHeaderView *headerViewTwo;
@property (nonatomic, strong) ZFPlayerController *player;
@property (nonatomic, strong) ZFPlayerControlView *controlView;
@property (nonatomic, strong) UIButton *collectButton;
@property (nonatomic, strong) UIView *bottomView;/**底部视图*/

//普通单元格与富文本单元格
@property (nonatomic, copy) NSString *cellID_Normal;
@property (nonatomic, copy) NSString *cellID_DTCoreText;

//类似tabelView的缓冲池，用于存放图片大小
@property (nonatomic, strong) NSCache *imageSizeCache;
@property (nonatomic,strong)NSCache *cellCache;

//表视图数据源
@property (nonatomic, strong) NSArray  *dataSource;
@property (nonatomic,assign)BOOL isScrolling;
@property (nonatomic,assign)CGFloat currenttime;
@property (nonatomic, strong) NSString  *hourId;//当前课程id

@end

@implementation LBCoureseDetailVC

- (void)getUserIDWithDeviceNumber{
    
}
- (void)showAlertView{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您还没有登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去登录", nil];
    [alert show];
}
- (NSMutableArray *)teacherDataArray{
    if (!_teacherDataArray) {
        _teacherDataArray = [NSMutableArray array];
    }
    return _teacherDataArray;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, LBNAVBAR_HEIGHT, ScreenW, ScreenH-LBNAVBAR_HEIGHT-44) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"课程详情";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(senWeChatShareSuccess) name:@"WeChatShareSuccess" object:nil];
    _imageSizeCache = [[NSCache alloc] init];
    _cellCache = [[NSCache alloc] init];
    _cellCache.totalCostLimit = 10;
    _cellCache.countLimit = 10;
    [self setupUI];
    [self setupNavigation];
    
}
#pragma mark - 分享成功后调用积分接口
- (void)senWeChatShareSuccess{
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    NSString *token = [UserModel getUserModel].token;
    [data setObject:token forKey:@"token"];
    [data setObject:self.model.courseId forKey:@"courseId"];
    [data setObject:@"1" forKey:@"courseType"];
    [WYHXNetWorkManager post:WKQshareCourseData_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
        NSString *code = responseObj[@"code"];
        NSString *msg = responseObj[@"msg"];
        if ([code integerValue]==200) {
//            NSLog(@"%@",responseObj);
            NSString *data = responseObj[@"data"];
            [MBProgressHUD showSuccess:msg toView:self.view];
            return ;
        }
    }];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    //加载网络数据
    [self requestData];
    //加载讲师数据
    [self reqestTeacherData];
}
#pragma mark - 播放快进按钮
- (void)clickKuaiPlayBtn:(UIButton *)sender{
    sender.selected = !sender.selected;
//    NSLog(@"快进了");
    //点击一次快进
    if (sender.selected) {
        self.player.currentPlayerManager.rate = 2.0;
    }else{//第二次是恢复正常
        self.player.currentPlayerManager.rate = 1.0;
    }
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
//    NSLog(@"%f",self.player.currentPlayerManager.currentTime);
    if (self.hourId) {
        [self getplaylenth];
    }
}


- (void)getplaylenth{
    

    NSString *time = [NSString stringWithFormat:@"%.f",self.player.currentPlayerManager.currentTime];
    NSInteger index = [time integerValue];
//    NSLog(@"%f",[time floatValue]);
    
    NSString *token = [UserModel getUserModel].token;
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.hourId forKey:@"hourId"];
    [param setObject:self.courseId forKey:@"courseId"];
    [param setObject:@(index) forKey:@"videoLength"];
    [param setObject:token forKey:@"token"];
    
    //传递给服务器最后播放的时长
    [WYHXNetWorkManager post:WKGetUserStudyrecod_WKURL params:param completionHandler:^(id responseObj, NSError *error) {
//        NSLog(@"%@%@",responseObj,error);
    }];

}
- (void)playTheIndex:(NSInteger)index {
    [self palyer:index];
}
- (void)palyer:(NSInteger)index{
    if ([self.model.isPay isEqualToString:@"0"]) {
        
        [MBProgressHUD showSuccess:@"请先兑换此课程" toView:self.view];
        return;
    }
    LBCourseHourOutputDTOList *model = self.dataArray[index];
    self.hourOutputModel = model;
    self.hourId = model.hourId;
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@",Public_URL,model.hourUrl];
    NSString *thunbnaiUrl = [NSString stringWithFormat:@"%@%@",Public_URL,model.videoImage];
    NSString *token = [UserModel getUserModel].token;
    if (!token) {
        LBLoginVC *loginVC = [[LBLoginVC alloc] init];
        loginVC.jumpType = @"1";
        [self.navigationController pushViewController:loginVC animated:YES];
    }else{
        if (model.hourType==2) {
            
            //            LBKeshiDetailVC *keshiVC = [[LBKeshiDetailVC alloc] init];
            //            TestTableViewController *keshiVC = [[TestTableViewController alloc] init];
            [self.player.currentPlayerManager pause];//跳转下一页面
            LBKeshDetailsVC *keshiVC = [[LBKeshDetailsVC alloc] init];
            keshiVC.htmlString = model.hourInfo;
            [self.navigationController pushViewController:keshiVC animated:YES];
            
            
        }else{
            
            
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            NSString *token = [UserModel getUserModel].token;
            [dict setObject:model.hourId forKey:@"hourId"];
            [dict setObject:token forKey:@"token"];
            __weak typeof(self)weakself = self;
            //获取用户观看视频或者音频最后一次时长
            [WYHXNetWorkManager get:WKGetUserLookvideoaudioLeng_WKURL params:dict completionHandler:^(id responseObj, NSError *error) {
                NSString *code = responseObj[@"code"];
                if ([code integerValue]==200) {
                    NSString *length = responseObj[@"data"];
                    NSInteger index = [length integerValue];
                    weakself.player.currentPlayerManager.seekTime = index;
                }
                
            }];
            
//            self.controlView.portraitControlView.bgImageView.hidden = NO;
            if (model.hourType==1) {
                self.controlView.portraitControlView.bgImageView.hidden = NO;
            }else{
                self.controlView.portraitControlView.bgImageView.hidden = YES;
            }
            [self.controlView.portraitControlView.bgImageView sd_setImageWithURL:[NSURL URLWithString:thunbnaiUrl] placeholderImage:[UIImage imageNamed:@"wk_list_bgimg"]];
            [self.controlView.landScapeControlView.bgImageView sd_setImageWithURL:[NSURL URLWithString:thunbnaiUrl] placeholderImage:[UIImage imageNamed:@"wk_list_bgimg"]];
            //        }else{
            ////            self.controlView.portraitControlView.bgImageView.hidden = YES;
            //        }
            [self.controlView showTitle:@"" coverURLString:thunbnaiUrl fullScreenMode:ZFFullScreenModeLandscape];
            [self.headerViewTwo.coverImageView sd_setImageWithURL:[NSURL URLWithString:thunbnaiUrl] placeholderImage:[UIImage imageNamed:@"wk_list_bgimg"]];
            
            //处理带中文的url
            NSString *encodeUrlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            
            
            //设置从那开始播放
            //        [self.player.currentPlayerManager seekToTime:100 completionHandler:nil];
            
            self.player.currentPlayerManager.assetURL = [NSURL URLWithString:encodeUrlString];
            self.controlView.backgroundColor = [UIColor clearColor];
        }
    }
}
#pragma mark - 竖屏播放或暂停按钮
- (void)clickPalyOrPauseBtn:(UIButton *)sender{
//    NSLog(@"正常播放了");
    self.player.currentPlayerManager.rate = 1.0;
}

- (void)setupUI{
    self.headerView = [UIView new];
    self.headerView.frame = CGRectMake(0, 0, ScreenW, 209*kScaleFit);
    
    //创建视频
    ZFAVPlayerManager *playerManager = [[ZFAVPlayerManager alloc] init];
    self.player = [ZFPlayerController playerWithPlayerManager:playerManager containerView:self.headerViewTwo.coverImageView];
    self.player.controlView = self.controlView;

//    self.headerViewTwo.backgroundColor = [UIColor cyanColor];
    self.headerViewTwo.layer.cornerRadius = 5;
    self.headerViewTwo.layer.masksToBounds = YES;
    [self.controlView.landScapeControlView.kuaijinBtn addTarget:self action:@selector(clickKuaiPlayBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.controlView.portraitControlView.kuaiButton addTarget:self action:@selector(clickKuaiPlayBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.controlView.portraitControlView.playOrPauseBtn addTarget:self action:@selector(clickPalyOrPauseBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.controlView.landScapeControlView.playOrPauseBtn addTarget:self action:@selector(clickPalyOrPauseBtn:) forControlEvents:UIControlEventTouchUpInside];
    @weakify(self)
    self.player.orientationWillChange = ^(ZFPlayerController * _Nonnull player, BOOL isFullScreen) {
        @strongify(self)
        [self setNeedsStatusBarAppearanceUpdate];
        //        [UIViewController attemptRotationToDeviceOrientation];
        self.tableView.scrollsToTop = !isFullScreen;
        if (self.hourOutputModel.hourType==1) {
            self.controlView.portraitControlView.bgImageView.hidden = NO;
        }else{
            self.controlView.portraitControlView.bgImageView.hidden = YES;
            self.controlView.landScapeControlView.bgImageView.hidden = YES;
        }
    };
    
    self.player.playerDidToEnd = ^(id  _Nonnull asset) {
        @strongify(self)
        
        [self.controlView resetControlView];
        [self.player.currentPlayerManager seekToTime:0 completionHandler:nil];
    };
    //1
    [self.headerView addSubview:self.headerViewTwo];
    
    //2
    self.tableView.tableHeaderView = self.headerView;
    
    [self.headerViewTwo makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(10);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.bottom.mas_equalTo(0);
    }];
    [self.view addSubview:self.tableView];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 50;
    self.tableView.tableFooterView = [UIView new];
    [self setupBottomView];
    
    
}
- (ZFPlayerControlView *)controlView {
    if (!_controlView) {
        _controlView = [ZFPlayerControlView new];
        _controlView.fastViewAnimated = YES;
    }
    return _controlView;
}

- (ZFTableHeaderView *)headerViewTwo {
    if (!_headerViewTwo) {
        _headerViewTwo = [[ZFTableHeaderView alloc] init];
        @weakify(self)
        _headerViewTwo.playCallback = ^{
            @strongify(self)
            //            [self playTheIndex:0];
        };
    }
    return _headerViewTwo;
}
- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    CGFloat y = CGRectGetMaxY(self.navigationController.navigationBar.frame);
    CGFloat h = CGRectGetMaxY(self.view.frame);
    if ([self.model.isPay isEqualToString:@"1"]) {
        self.tableView.frame = CGRectMake(0, LBNAVBAR_HEIGHT, ScreenW, h-LBNAVBAR_HEIGHT);
    }else{

        self.tableView.frame = CGRectMake(0, LBNAVBAR_HEIGHT, ScreenW, h-44-LBNAVBAR_HEIGHT);
    }
}

//- (BOOL)shouldAutorotate {
//    return self.player.shouldAutorotate;
//}
//
//- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
//    if (self.player.isFullScreen && self.player.orientationObserver.fullScreenMode == ZFFullScreenModeLandscape) {
//        return UIInterfaceOrientationMaskLandscape;
//    }
//    return UIInterfaceOrientationMaskPortrait;
//}
//
//- (UIStatusBarStyle)preferredStatusBarStyle {
//    if (self.player.isFullScreen) {
//        return UIStatusBarStyleLightContent;
//    }
//    return UIStatusBarStyleDefault;
//}
//
//- (BOOL)prefersStatusBarHidden {
//    return self.player.isStatusBarHidden;
//}

//- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
//    return UIStatusBarAnimationSlide;
//}

#pragma mark - 讲师接口
- (void)reqestTeacherData{
    //    WKTeacherDetail_WKURL
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    [data setObject:self.courseId forKey:@"refId"];
    [data setObject:self.type forKey:@"type"];
//    NSLog(@"%@",data);
//    NSLog(@"%@",WKTeacherDetail_WKURL);
    [WYHXNetWorkManager get:WKTeacherDetail_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
        NSLog(@"%@",responseObj);
        NSDictionary *dict = (NSDictionary *)responseObj;
        NSString *code = responseObj[@"code"];
        if ([code integerValue]==200) {
            
            NSArray *arr = [LBTeacherModel mj_objectArrayWithKeyValuesArray:dict[@"data"]];
            
            [self.teacherDataArray addObjectsFromArray:arr];
//            NSLog(@"%@",self.teacherDataArray);
        }
        [self.tableView reloadData];
    }];
    
}
#pragma mark - 课程详情接口
- (void)requestData{
    
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    [data setObject:self.courseId forKey:@"courseId"];
    NSString *token = [UserModel getUserModel].token;
    if (token) {
        [data setObject:token forKey:@"canNullToken"];
    }
    
    [WYHXNetWorkManager get:WKCourseListDetail_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
        NSLog(@"%@",responseObj);
        NSDictionary *dict = (NSDictionary *)responseObj;
        NSString *code = responseObj[@"code"];
        NSDictionary *data = dict[@"data"];
        
        if ([code integerValue]==200) {
            self.model = [LBCourseOutputDTOListModel mj_objectWithKeyValues:dict[@"data"]];
            self.dataSource = @[self.model.courseInfo];
            if (data[@"courseHourOutputDTOList"]) {
                NSArray *courseHourOutputDTOList = data[@"courseHourOutputDTOList"];
                NSArray *arr = [LBCourseHourOutputDTOList mj_objectArrayWithKeyValuesArray:courseHourOutputDTOList];
                self.dataArray = [NSMutableArray array];
                [self.dataArray addObjectsFromArray:arr];
            }
            self.priceLab.text = [NSString stringWithFormat:@"¥%@", self.model.coursePrice];
            self.headerViewTwo.playBtn.hidden = YES;
            if ([self.model.isCollect isEqualToString:@"1"]) {
                [self.collectButton setTitle:@"已收藏" forState:UIControlStateNormal];
            }else{
                [self.collectButton setTitle:@"收藏" forState:UIControlStateNormal];
            }
#pragma mark - 支付后处理底部View
            
            if ([self.model.isPay isEqualToString:@"1"]) {
                self.bottomView.hidden=YES;
                self.tableView.frame = CGRectMake(0, 64, self.view.frame.size.width, ScreenH-64);
            }else{
                self.bottomView.hidden=NO;
                self.tableView.frame = CGRectMake(0, 64, self.view.frame.size.width, ScreenH-44-64);
            }
            //视频赋值， 这里不能直接赋值url 给视频 否则 会自动播放
//            if (self.dataArray.count==0) {
//
//            }else{
//                LBCourseHourOutputDTOList *model = self.dataArray[0];
                NSString *thumbnail_url;
                //这里使用外围的json 最外层courseImage 图片
                NSString *urlString = [NSString stringWithFormat:@"%@%@",Public_URL,self.model.courseImage];
//                NSString *thunbnaiUrl = [NSString stringWithFormat:@"%@%@",Public_URL,model.videoImage];
                //大背景图
                [self.headerViewTwo.coverImageView sd_setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:[UIImage imageNamed:@"wk_list_bgimg"]];
//                [self.controlView showTitle:@"" coverURLString:thunbnaiUrl fullScreenMode:ZFFullScreenModeLandscape];
//            }
            
            [self.tableView reloadData];
            
        }else if ([code integerValue]==401){
            [self jumpLloginviewController];
        }
    }];
}

- (void)setupBottomView{
    
    //底部view
    UIView *bottomView = [UIView new];
    self.bottomView = bottomView;
    bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomView];
    [bottomView makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_offset(0);
        make.height.mas_equalTo(44*kScaleFit);
    }];
    
    UIButton *shopButton = [[UIButton alloc] init];
    [bottomView addSubview:shopButton];
    [shopButton makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-0);
        make.top.mas_equalTo(0);
        make.width.mas_equalTo(100*kScaleFit);
        make.bottom.mas_equalTo(0);
    }];
    [shopButton setTitle:@"立即兑换" forState:UIControlStateNormal];
    [shopButton setTitleColor:rgb(255,255,255) forState:UIControlStateNormal];
    shopButton.titleLabel.font = LBFont(15*kScaleFit);
    shopButton.backgroundColor = rgb(233,84,18);
//    [shopButton setBackgroundImage:LBImage(@"wk_shadow_btn") forState:UIControlStateNormal];
    [shopButton addTarget:self action:@selector(clickShopBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *collectButton = [[UIButton alloc] init];
    self.collectButton = collectButton;
    [bottomView addSubview:collectButton];
    [collectButton makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(shopButton.mas_left);
        make.top.mas_equalTo(0);
        make.width.mas_equalTo(100*kScaleFit);
        make.bottom.mas_equalTo(0);
    }];
    
    [collectButton setTitle:@"收藏" forState:UIControlStateNormal];
    [collectButton setTitleColor:rgb(255,255,255) forState:UIControlStateNormal];
    collectButton.titleLabel.font = LBFont(15*kScaleFit);
    collectButton.backgroundColor = rgb(3,110,188);
    [collectButton addTarget:self action:@selector(clickCollectBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    //价格
    self.priceLab = [UILabel labelWithText:@"¥699" andTextColor:rgb(233,38,18) andName:nil andFontSize:18*kScaleFit];
    [bottomView addSubview:self.priceLab];
    [self.priceLab makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15*kScaleFit);
        make.centerY.mas_equalTo(bottomView);
    }];
}
#pragma mark - 收藏
- (void)clickCollectBtn:(UIButton *)sender{
    NSString *token = [UserModel getUserModel].token;
    if (token.length==0||!token) {
        LBLoginVC *vc = [[LBLoginVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
    }else{
        if ([self.model.isCollect isEqualToString:@"1"]) {
            NSMutableDictionary *data = [NSMutableDictionary dictionary];
//            [MBProgressHUD showSuccess:@"已收藏" toView:self.view];
            [data setObject:self.courseId forKey:@"courseId"];
            [data setObject:token forKey:@"token"];
            [data setObject:self.type forKey:@"courseType"];//区分课程包还是 或者免费课程
            [WYHXNetWorkManager post:WKCancelCoureseCellect_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
                NSString *code = responseObj[@"code"];
                NSString *msg = responseObj[@"msg"];
//                NSLog(@"%@",responseObj);
                if (code.integerValue==200) {
                    [MBProgressHUD showSuccess:msg toView:self.view];
                    [sender setTitle:@"收藏" forState:UIControlStateNormal];
                    [self requestData];
                }
            }];
        }else{
            
            NSMutableDictionary *data = [NSMutableDictionary dictionary];
            NSString *courseType = self.type;
            
            NSString *courseId = self.courseId;
            [data setObject:token forKey:@"token"];
            [data setObject:courseId forKey:@"courseId"];
            [data setObject:courseType forKey:@"collectType"];//区分课程包还是 或者免费课程
            
            [WYHXNetWorkManager post:WKCoureseCellect_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
                NSString *code = responseObj[@"code"];
//                NSLog(@"%@",responseObj);
                if (code.integerValue==200) {
                    NSString *msg = responseObj[@"msg"];
                    [MBProgressHUD showSuccess:msg toView:self.view];
                    [sender setTitle:@"已收藏" forState:UIControlStateNormal];
                    [self requestData];
                }
            }];
        }
        
    }
    
}
#pragma mark - 立即购买
- (void)clickShopBtn:(UIButton *)sender{
    NSString *token = [UserModel getUserModel].token;
    if (!token) {
        LBLoginVC *loginVC = [[LBLoginVC alloc] init];
        loginVC.jumpType = @"1";
        [self.navigationController pushViewController:loginVC animated:YES];
    }else{
#pragma mark -
        NSString *isVisitor = [UserModel getUserModel].isVisitor;
        if ([isVisitor isEqualToString:@"1"]) {
            [self alertController];
        }else{
            [self gotoShopping];
        }
    }
}
- (void)gotoShopping{
    LBPayVC *pay = [LBPayVC new];
    pay.type = @"1";//课时详情跳转支付页面 1
    //        pay.model = self.model;
    pay.name = self.model.courseName;
    pay.price = self.model.coursePrice;
    pay.courserId = self.model.courseId;
    pay.jumpType = self.jumpType;
    [self.navigationController pushViewController:pay animated:YES];
}
- (void)alertController{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请选择登录后购买，在其他设备也可以观看" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        LBLoginVC *loginVC = [[LBLoginVC alloc] init];
        loginVC.jumpType = @"1";
        [self.navigationController pushViewController:loginVC animated:YES];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"游客模式购买(仅限本设备观看)" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self gotoShopping];
    }]];
    
    //推出控制器
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)setupNavigation{
    UIButton *btn = [[UIButton alloc] init];
    [btn addTarget:self action:@selector(clickRightItemBtn:) forControlEvents:UIControlEventTouchUpInside];
    [btn setImage:LBImage(@"wk_share") forState:UIControlStateNormal];
    btn.frame = CGRectMake(0, 0, 30, 30);
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return 1;
    }
    if (section==1) {
        return self.dataArray.count;
    }else if (section==2){
        return self.teacherDataArray.count;
    }else{
        return 1;
    }
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    }

    if (indexPath.section==0) {
        LBCouresePackageCell *cell = [LBCouresePackageCell cellWithTableView:tableView];
        cell.model = self.model;
        return cell;
    }
    if (indexPath.section==1) {
        // hourType 1 视频 2 音频 3图文
        LBCourseHourOutputDTOList *model = self.dataArray[indexPath.row];

//        model.selected = NO;
        if (model.hourType==0) {
            LBCoureseVideoCell *cell = [LBCoureseVideoCell cellWithTableView:tableView];
            cell.model = model;
            
            return cell;
        }else if (model.hourType==1){
            LBCourseYinpinCell *cell = [LBCourseYinpinCell cellWithTableView:tableView];
            cell.model = model;
            
            return cell;
        }else{
            LBCourseImageViewCell *cell = [LBCourseImageViewCell cellWithTableView:tableView];
            cell.model = model;
            
            return cell;
        }
    }
    if (indexPath.section==2) {
        LBTeacherIntroduceCell *cell = [LBTeacherIntroduceCell cellWithTableView:tableView];
            LBTeacherModel *model = self.teacherDataArray[indexPath.row];
            cell.model = model;
        return cell;

    }
    if (indexPath.section==3) {
        ZSDTCoreTextCell *dtCell = (ZSDTCoreTextCell *) [self tableView:tableView prepareCellForIndexPath:indexPath];
        return dtCell;
    }
    
    return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footer = [UIView new];
    footer.backgroundColor =  rgb(240, 240, 240);
    return footer;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section==2) {
        UIView *headerView = [UIView new];
        self.sectionTitle = [UILabel labelWithText:@"讲师介绍" andTextColor:rgb(51,51,51) andName:nil andFontSize:15*kScaleFit];
        
        [headerView addSubview:self.sectionTitle];
        [self.sectionTitle makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(15*kScaleFit);
            make.centerY.mas_equalTo(headerView);
        }];
        return headerView;
    }else if (section==3){
        UIView *headerView = [UIView new];
        self.sectionTitle = [UILabel labelWithText:@"课程介绍" andTextColor:rgb(51,51,51) andName:nil andFontSize:15*kScaleFit];
        
        [headerView addSubview:self.sectionTitle];
        [self.sectionTitle makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(15*kScaleFit);
            make.centerY.mas_equalTo(headerView);
        }];
        return headerView;
    }
    else{
        return nil;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==3||section==2) {
        return 40;
    }else{
        return 0.01;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==3) {
        ZSDTCoreTextCell *cell = (ZSDTCoreTextCell *)[self tableView:tableView prepareCellForIndexPath:indexPath];
        return [cell requiredRowHeightInTableView:tableView];
    }else if (indexPath.section==1){
        return 66;
    }else if(indexPath.section==2){

        return UITableViewAutomaticDimension;
    }else{
        return UITableViewAutomaticDimension;
    }

}
#pragma mark - private Methods
//创建富文本单元格，并更新单元格上的数据
- (ZSDTCoreTextCell *)tableView:(UITableView *)tableView prepareCellForIndexPath:(NSIndexPath *)indexPath{
    NSString *key = [NSString stringWithFormat:@"dtCoreTextCellKEY%ld", (long)indexPath.row];
    ZSDTCoreTextCell *cell = [_cellCache objectForKey:key];
    
    if (!cell){
        //    cell = [self.tableView dequeueReusableCellWithIdentifier:_cellID_DTCoreText];
        //        if (!cell) {
        cell = [[ZSDTCoreTextCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:_cellID_DTCoreText];
        //        }
        cell.attributedTextContextView.edgeInsets = UIEdgeInsetsMake(0, 15, 0, 15);
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.hasFixedRowHeight = NO;
        cell.textDelegate = self;
        cell.attributedTextContextView.shouldDrawImages = YES;
        //记录在缓存中
        [_cellCache setObject:cell forKey:key];
    }
    //2.设置数据
    //2.1为富文本单元格设置Html数据
    [cell setHTMLString:self.dataSource[indexPath.row]];
    //2.2为每个占位图(图片)设置大小，并更新
    for (DTTextAttachment *oneAttachment in cell.attributedTextContextView.layoutFrame.textAttachments) {
        NSValue *sizeValue = [_imageSizeCache objectForKey:oneAttachment.contentURL];
        if (sizeValue) {
            cell.attributedTextContextView.layouter=nil;
            oneAttachment.displaySize = [sizeValue CGSizeValue];
            [cell.attributedTextContextView relayoutText];
        }
    }
    [cell.attributedTextContextView relayoutText];
    return cell;
}

#pragma mark - DTAttributedTextContentViewDelegate
//对于没有在Html标签里设置宽高的图片，在这里为其设置占位
- (UIView *)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView viewForAttachment:(DTTextAttachment *)attachment frame:(CGRect)frame{
    if([attachment isKindOfClass:[DTImageTextAttachment class]]){
        ZSDTLazyImageView *imageView = [[ZSDTLazyImageView alloc] initWithFrame:frame];
        imageView.delegate = self;
        imageView.image = [(DTImageTextAttachment *)attachment image];
        imageView.textContentView = attributedTextContentView;
        imageView.url = attachment.contentURL;
        return imageView;
    }
    return nil;
}
//对于无宽高懒加载得到的图片，缓存记录其大小,然后执行表视图更新
- (void)lazyImageView:(ZSDTLazyImageView *)lazyImageView didChangeImageSize:(CGSize)size{
    BOOL needUpdate = NO;
    NSURL *url = lazyImageView.url;
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"contentURL == %@", url];
    /* update all attachments that matchin this URL (possibly multiple
     images with same size)
     */
    for (DTTextAttachment *oneAttachment in [lazyImageView.textContentView.layoutFrame textAttachmentsWithPredicate:pred]){
        // update attachments that have no original size, that also sets the display size
        if (CGSizeEqualToSize(oneAttachment.originalSize, CGSizeZero)){
            oneAttachment.originalSize = size;
            NSValue *sizeValue = [_imageSizeCache objectForKey:oneAttachment.contentURL];
            if (!sizeValue) {
                //将图片大小记录在缓存中，但是这种图片的原始尺寸可能很大，所以这里设置图片的最大宽
                //并且计算高
                CGFloat aspectRatio = size.height / size.width;
                CGFloat width = ZSToolScreenWidth - 15*2;
                CGFloat height = width * aspectRatio;
                CGSize newSize = CGSizeMake(width, height);
                [_imageSizeCache setObject:[NSValue valueWithCGSize:newSize]forKey:url];
            }
            needUpdate = YES;
        }
    }
    
    if (needUpdate){
        //有新的图片尺寸被缓存记录的时候，需要刷新表视图
        //[self reloadCurrentCell];
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(reloadCurrentCell) object:nil];
        self.isScrolling = NO;
        [self performSelector:@selector(reloadCurrentCell) withObject:nil afterDelay:0.2];
    }
}
- (void)reloadCurrentCell{
    //如果当前表视图在滑动就不执行刷新，因为滑动时候会自动调用表视图的刷新方法
    if (self.isScrolling) {
        return;
    }
    //如果当前表视图没有在滑动，就手动刷新当前在屏幕显示的单元格
    NSArray *indexPaths = [self.tableView indexPathsForVisibleRows];
    if(indexPaths){
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
        });
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    _isScrolling = YES;
}
- (NSArray *)dataSource{
    if(_dataSource == nil){

    }
    return _dataSource;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section==1) {
        [self playTheIndex:indexPath.row];
        
    }

}

- (void)jumpLloginviewController{
    LBLoginVC *loginVC = [[LBLoginVC alloc] init];
    loginVC.jumpType = @"1";
    [self.navigationController pushViewController:loginVC animated:YES];
}
#pragma mark - 分享按钮点击事件
- (void)clickRightItemBtn:(UIButton *)sender{
    NSString *token = [UserModel getUserModel].token;
    if (!token||token.length==0) {
        [self jumpLloginviewController];
    }else{
        [LWShareService shared].shareBtnClickBlock = ^(NSIndexPath *index) {
            NSInteger tag = index.row;
            [[LWShareService shared] hideSheetView];
            NSString *shareUrl = [NSString stringWithFormat:@"%@%@&userId=",WKCourseShare_url,self.model.courseId,token];
            //http://www.vlearnjy.com/html/detail/course_detail.html?courseId=53
            switch (tag) {
                case 0:
                {
                    
                    
                    WXWebpageObject *webpageObject = [WXWebpageObject object];
                    webpageObject.webpageUrl = shareUrl;
                    
                    WXMediaMessage *message = [WXMediaMessage message];
                    message.title = self.model.courseTitle;
                    message.description = self.model.coursePresent;
                    [message setThumbImage:[UIImage imageNamed:@"wanke_logo"]];
                    message.mediaObject = webpageObject;
                    
                    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
                    req.bText = NO;
                    req.message = message;
                    req.scene = WXSceneSession;
                    [WXApi sendReq:req];
                }
                    break;
                case 1:
                {
                    WXWebpageObject *webpageObject = [WXWebpageObject object];
                    webpageObject.webpageUrl = shareUrl;
                    
                    WXMediaMessage *message = [WXMediaMessage message];
                    message.title = self.model.courseTitle;
                    message.description = self.model.coursePresent;
//                    [message setThumbImage:[UIImage imageNamed:self.model.courseImage]];
                    [message setThumbImage:[UIImage imageNamed:@"wanke_logo"]];
                    message.mediaObject = webpageObject;
                    
                    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
                    req.bText = NO;
                    req.message = message;
                    req.scene = WXSceneTimeline;
                    [WXApi sendReq:req];
                    
                }
                    break;
                default:
                    break;
            }
        };
        
        [[LWShareService shared] showInViewController:self];
    }
}
@end
